package home;
//解析 JSON 数据

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import home.bean.ApiResponse;
import home.bean.Carousel;
import home.bean.Data;
import home.bean.Goods;

public class JsonParser {
    public static ApiResponse parse(String json) throws JSONException {
        JSONObject root = new JSONObject(json);
        ApiResponse response = new ApiResponse();
        response.setResultCode(root.getInt("resultCode"));
        response.setMessage(root.getString("message"));

        JSONObject data = root.getJSONObject("data");
        Data dataBean = new Data();

        // 解析轮播图（Carousel）
        JSONArray carouselsArray = data.getJSONArray("carousels");
        for (int i = 0; i < carouselsArray.length(); i++) {
            JSONObject carouselObj = carouselsArray.getJSONObject(i);
            Carousel carousel = new Carousel();
            carousel.setCarouselUrl(carouselObj.getString("carouselUrl"));
            carousel.setRedirectUrl(carouselObj.getString("redirectUrl"));
            dataBean.getCarousels().add(carousel);
        }

        // 解析热门商品（hotGoodses）
        parseGoodsArray(data.getJSONArray("hotGoodses"), dataBean.getHotGoodses());
        // 解析新品（newGoodses）
        parseGoodsArray(data.getJSONArray("newGoodses"), dataBean.getNewGoodses());
        // 解析推荐商品（recommendGoodses）
        parseGoodsArray(data.getJSONArray("recommendGoodses"), dataBean.getRecommendGoodses());

        response.setData(dataBean);
        return response;
    }

    // 通用商品数组解析方法
    private static void parseGoodsArray(JSONArray array, List<Goods> goodsList) throws JSONException {
        for (int i = 0; i < array.length(); i++) {
            JSONObject goodsObj = array.getJSONObject(i);
            Goods goods = new Goods();
            goods.setGoodsId(goodsObj.getInt("goodsId"));
            goods.setGoodsName(goodsObj.getString("goodsName"));
            goods.setGoodsIntro(goodsObj.optString("goodsIntro", "")); // 处理可能的 null
            goods.setGoodsCoverImg(goodsObj.optString("goodsCoverImg", ""));
            goods.setSellingPrice(goodsObj.getInt("sellingPrice"));
            goods.setTag(goodsObj.optString("tag", ""));
            goodsList.add(goods);
        }
    }
}
